package client.comm.commlib.network

import client.comm.baoding.utils.Constants
import client.comm.commlib.ContextProvider
import client.comm.commlib.utils.SharedUtil
import client.comm.commlib.utils.Util
import com.blankj.utilcode.util.LogUtils
import okhttp3.*
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.io.IOException
import java.net.Proxy
import java.util.concurrent.TimeUnit

class HhRetroHttp private constructor() {
    private val mRetrofit: Retrofit by lazy {
        val okHttpClient = OkHttpClient.Builder()
            .connectTimeout(5, TimeUnit.SECONDS)
            .writeTimeout(7, TimeUnit.SECONDS)
            .readTimeout(7, TimeUnit.SECONDS)
            .proxy(Proxy.NO_PROXY)
            .addInterceptor(object : Interceptor {
                @Throws(IOException::class)
                override fun intercept(chain: Interceptor.Chain): Response {

                    val ts = System.currentTimeMillis().toString() + ""
                    val token =
                        SharedUtil.read("token", "") as String
                    var version = 0

                    ContextProvider.get().activity?.let {
                        version = it
                            .packageManager
                            .getPackageInfo(it.packageName, 0).versionCode
                    }

                    //动态修改BaseUrl ***************************************

//                    // 匹配获得新的BaseUrl
//                    var newBaseUrl: HttpUrl? = null
//                    if (!SharedUtil.read(Constants.IS_ZEROHOST, "").isNullOrEmpty() ) {
//                        newBaseUrl = HH_URL_DEBUG.toHttpUrlOrNull()
//                        LogUtils.i("======" + 5001)
//                    } else {//默认
//                        newBaseUrl = BASE_URL.toHttpUrlOrNull()
//                        LogUtils.i("======" + 5000)
//                    }
//                    // 获取request
//                    val oldHttpUrl: HttpUrl = chain.request().url
//                    // 重建新的HttpUrl，修改需要修改的url部分
//                    val newFullUrl: HttpUrl = oldHttpUrl
//                        .newBuilder() // 更换网络协议
//                        .scheme(newBaseUrl!!.scheme) // 更换主机名
//                        .host(newBaseUrl.host) // 更换端口
//                        .port(newBaseUrl.port)
//                        .build()

                    val request: Request = chain.request().newBuilder()
                        .addHeader("access", "&OSpYVy#6g^Q7Fo#")
                        .addHeader("ts", ts)
                        .addHeader("database", "ll_mall")
                        .addHeader("version", "${version}")
                        .addHeader("sign", Util.getSign(ts))
                        .addHeader("token", token)
//                        .url(newFullUrl)
                        .build()

                    return chain.proceed(request)


                }
            })
            .addInterceptor(HttpLoggingInterceptor().apply {
                level = HttpLoggingInterceptor.Level.BODY
            })
            .build()


        Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .client(okHttpClient)
            .build()
    }

//    var newHttpUrl = "http://120.77.64.128:5000/"

    companion object {
//        val BASE_URL = "http://49.4.7.100:5000/"       //正式端口43.138.12.116
        val BASE_URL = "http://192.168.0.66:5000/"      //本地端口
//        val AGREEMENT = "https://mall.sd369sw.com/d/bd_agreement.html"//隐私政策

        private val INSTANT: HhRetroHttp by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) { HhRetroHttp() }

        fun get(): HhRetroHttp {
            return INSTANT
        }

        fun <T> createApi(tClass: Class<T>): T {
            return lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) { get().mRetrofit.create(tClass) }.value
        }
    }

}

